// pages/student/edit-profile/edit-profile.js
Page({
  data: {
    userInfo: {
      name: '',
      phone: '',
      email: '',
      avatar: '',
      gradeLevel: '',
      schoolName: ''
    }
  },
  onLoad() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo: {
          name: userInfo.name || '',
          phone: userInfo.phone || '',
          email: userInfo.email || '',
          avatar: userInfo.avatar || '',
          gradeLevel: userInfo.gradeLevel || userInfo.level || '',
          schoolName: userInfo.schoolName || ''
        }
      })
    }
  },
  handleNameInput(e) {
    this.setData({
      'userInfo.name': e.detail.value
    })
  },
  handlePhoneInput(e) {
    this.setData({
      'userInfo.phone': e.detail.value
    })
  },
  handleEmailInput(e) {
    this.setData({
      'userInfo.email': e.detail.value
    })
  },
  handleGradeLevelInput(e) {
    this.setData({
      'userInfo.gradeLevel': e.detail.value
    })
  },
  handleSchoolNameInput(e) {
    this.setData({
      'userInfo.schoolName': e.detail.value
    })
  },
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.setData({
          'userInfo.avatar': tempFilePath
        })
        wx.showToast({
          title: '头像已更新',
          icon: 'success'
        })
      }
    })
  },
  saveProfile() {
    const { name, phone, email } = this.data.userInfo
    
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '保存中...' })
    
    // 模拟保存
    setTimeout(() => {
      const savedUserInfo = wx.getStorageSync('userInfo')
      const updatedUserInfo = {
        ...savedUserInfo,
        name: this.data.userInfo.name,
        avatar: this.data.userInfo.avatar,
        phone: this.data.userInfo.phone,
        email: this.data.userInfo.email,
        gradeLevel: this.data.userInfo.gradeLevel,
        schoolName: this.data.userInfo.schoolName
      }
      wx.setStorageSync('userInfo', updatedUserInfo)
      
      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }, 1000)
  }
})
